package cn.edu.cuit.elena.web.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.cuit.elena.db.dao.BaseDao;
import cn.edu.cuit.elena.trace.Tracer;
import cn.edu.cuit.elena.web.System;
import cn.edu.cuit.elena.web.tool.JsonHelper;

public class PrivilegeManagementServlet
    extends HttpServlet
{

    /**
     * 
     */
    private static final long serialVersionUID = 7019626485649315837L;

    BaseDao baseDao = new BaseDao( System.getSystemDataSource() );

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
    {
        doPost( request, response );
    }

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
    {

        response.setContentType( "text/html" );
        PrintWriter out = response.getWriter();
        String para = request.getParameter( "kind" );
        if( "privilegetree".equals( para ) )
        {

            List<List<String>> rows = baseDao
                .queryForList(
                    "select c.id as p_id,c.name as p_name,c.urlname as p_urlname,d.id as c_id,d.name as c_name,d.urlname as c_urlname from elena.tc_priviledge c right join elena.tc_priviledge d on c.id = d.belongto order by p_id ",
                    new LinkedList<String>() );

            //                        String pre_p_id = "";
            //                        String pre_p_name = "";
            //                        String pre_p_url = "";
            //                        List<Map<String, String>> leafs = new LinkedList<Map<String, String>>();
            //                        Map<String, Object> branch = new HashMap<String, Object>();
            //                        List<Map<String, Object>> tree = new LinkedList<Map<String, Object>>();
            //                        Map<String, String> leaf;
            //                        for( List<String> row : rows )
            //                        {
            //                            String p_id = row.get( 0 ) == null ? "" : row.get( 0 );
            //                            if( pre_p_id.equals( p_id ) )
            //                            {
            //                                leaf = new HashMap<String, String>();
            //            
            //                                //c_name
            //                                leaf.put( "text", row.get( 4 ) == null ? "" : row.get( 4 ) + " | No.: " + row.get( 3 ) + " | URL: "
            //                                    + row.get( 5 ) );
            //                                leaf.put( "url", row.get( 5 ) == null ? "" : row.get( 5 ) );
            //                                leaf.put( "leaf", "true" );
            //                                leafs.add( leaf );
            //                                pre_p_id = p_id;
            //                                pre_p_name = row.get( 1 ) == null ? "" : row.get( 1 );
            //                                pre_p_url = row.get( 2 ) == null ? "" : row.get( 2 );
            //                            }
            //                            else
            //                            {
            //                                branch.put( "text", pre_p_name );
            //                                branch.put( "children", leafs );
            //                                branch.put( "url", pre_p_url );
            //            
            //                                Map<String, Object> temp = new HashMap<String, Object>();
            //                                temp.putAll( branch );
            //                                tree.add( temp );
            //            
            //                                branch.clear();
            //            
            //                                leafs = new LinkedList<Map<String, String>>();
            //                                leaf = new HashMap<String, String>();
            //                                //c_name
            //                                leaf.put( "text", row.get( 4 ) == null ? "" : row.get( 4 ) + " | No.: " + row.get( 3 ) + " | URL: "
            //                                    + row.get( 5 ) );
            //                                leaf.put( "url", row.get( 5 ) == null ? "" : row.get( 5 ) );
            //                                leaf.put( "leaf", "true" );
            //                                leafs.add( leaf );
            //                                pre_p_id = p_id;
            //                            }
            //                        }
            //                        branch.put( "text", pre_p_name );
            //                        branch.put( "children", leafs );
            //                        branch.put( "url", pre_p_url );
            //                        tree.add( branch );
            //            
            //                        String json = JsonHelper.getNewInstance().toJson( tree );
            //            
            //                        Tracer.debugTrace( PrivilegeManagementServlet.class, "privilege tree json : " + json, null );
            //            
            //                        out.write( json );
            //                        out.flush();
            //                        out.close();

            String pre = null;
            String current = null;
            List<Map<String, Object>> list0 = new LinkedList<Map<String, Object>>();
            List<Map<String, String>> list = null;
            int i = 0;
            for( List<String> row : rows )
            {
                i++;
                Map<String, String> map = new HashMap<String, String>();
                current = row.get( 0 );
                if( current == null )
                {
                    continue;
                }
                if( !current.equals( pre ) )
                {
                    Map<String, Object> map0 = new HashMap<String, Object>();
                    map0.put( "text", "ID : " + row.get( 0 ) + " Discription : " + row.get( 1 ) );
                    map0.put( "children", list );
                    list0.add( map0 );
                    list = new LinkedList<Map<String, String>>();
                }
                map.put( "text", row.get( 4 ) == null ? "" : row.get( 4 ) + " | No.: " + row.get( 3 ) + " | URL: "
                    + row.get( 5 ) );
                map.put( "url", row.get( 5 ) == null ? "" : row.get( 5 ) );
                map.put( "leaf", "true" );
                list.add( map );
                pre = current;
                if( i == rows.size() )
                {
                    Map<String, Object> map0 = new HashMap<String, Object>();
                    map0.put( "text", "ID : " + row.get( 0 ) + " Discription : " + row.get( 1 ) );
                    map0.put( "children", list );
                    list0.add( map0 );
                }
            }

            String json = JsonHelper.getNewInstance().toJson( list0 );

            Tracer.debugTrace( PrivilegeManagementServlet.class, "privilege tree json : " + json, null );

            out.write( json );
            out.flush();
            out.close();

        }
        else if( "add".equals( para ) )
        {
            String discript = request.getParameter( "discript" );
            String url = request.getParameter( "url" );
            String id = request.getParameter( "id" );
            String parent = request.getParameter( "parent" );

            String sql = "insert into elena.tc_priviledge (id,name,urlname,belongto)values('" + id + "','" + discript
                + "','" + url + "','" + parent + "')";
            baseDao.execute( sql );
            Tracer.debugTrace( PrivilegeManagementServlet.class, "add sql : " + sql, null );
            out.write( "1" );
            out.close();
        }
        else if( "delete".equals( para ) )
        {
            String paraString = request.getParameter( "parastring" );
            String url = paraString.substring( paraString.indexOf( "URL:" ) + 4 ).trim();

            String sql = "delete from elena.tc_priviledge where urlname = '" + url + "'";

            Tracer.debugTrace( PrivilegeManagementServlet.class, "delete sql : " + sql, null );

            baseDao.execute( sql );
            out.write( "1" );
            out.close();
        }
        else if( "grant".equals( para ) )
        {
            String paraString = request.getParameter( "parastring" );
            int index_1 = paraString.indexOf( "No.:" ) + 4;
            int index_2 = paraString.indexOf( "| URL:" );
            String id = paraString.substring( index_1, index_2 ).trim();
            String userName = request.getParameter( "username" );

            String sql = "insert into user_priviledge (user,priviledge) values('" + userName + "','" + id + "')";

            Tracer.debugTrace( PrivilegeManagementServlet.class, "grant sql : " + sql, null );

            baseDao.execute( sql );
            out.write( "1" );
            out.flush();
            out.close();
        }
        else if( "strip".equals( para ) )
        {
            String paraString = request.getParameter( "parastring" );
            int index_1 = paraString.indexOf( "No.:" ) + 4;
            int index_2 = paraString.indexOf( "| URL:" );
            String id = paraString.substring( index_1, index_2 );
            String userName = request.getParameter( "username" );

            String sql = "delete from user_priviledge where user='" + userName + "' and priviledge = '" + id + "'";

            Tracer.debugTrace( PrivilegeManagementServlet.class, "strip sql : " + sql, null );

            baseDao.execute( sql );
            out.write( "1" );
            out.flush();
            out.close();
        }
    }
}
